package com.xs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xs.common.R;
import com.xs.domain.Admin;
import com.xs.domain.Consumer;
import com.xs.domain.dto.AdminDTO;
import com.xs.mapper.AdminMapper;
import com.xs.mapper.ConsumerMapper;
import com.xs.service.AdminService;
import com.xs.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;

import static com.xs.common.Consts.SALT;

/**
* @author admin
* @description 针对表【admin(管理员表)】的数据库操作Service实现
* @createDate 2022-11-14 10:28:52
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
implements AdminService{
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private ConsumerMapper consumerMapper;

    /**
     * 登录
     * @param adminRequest
     * @return
     */
    @Override
    public R verityPasswd(AdminDTO adminRequest) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminRequest.getUsername());
        String secretPassword = DigestUtils.md5DigestAsHex((SALT + adminRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
        queryWrapper.eq("password", secretPassword);
        Admin one = getOne(queryWrapper);
        if (one != null) {
            BeanUtil.copyProperties(one, adminRequest, true);
            //设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            adminRequest.setToken(token);
            System.out.println("token = " + token);
            return R.success("登录成功", adminRequest);
        } else {
            return R.error(400, "用户名或密码错误");
        }
    }

    /**
     * 注册
     */
    @Override
    public R addUser(AdminDTO registryRequest) {
        if (this.existUser(registryRequest.getUsername())) {
            return R.error(400, "用户名已注册");
        }
        Admin admin = new Admin();
        BeanUtils.copyProperties(registryRequest, admin);
        //MD5加密
        String password = DigestUtils.md5DigestAsHex((SALT + registryRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
        admin.setPassword(password);
        admin.setAvatar("img/user.jpg");
        try {
            if (adminMapper.insert(admin) > 0) {
                return R.success("注册成功");
            } else {
                return R.error(400, "注册失败");
            }
        } catch (DuplicateKeyException e) {
            return R.error(400, "注册失败");
        }
    }

    /**
     * 判断重名
     * @param username
     * @return
     */
    @Override
    public boolean existUser(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return adminMapper.selectCount(queryWrapper) > 0;
    }


    /**
     * 根据姓名查找用户信息
     * @param username
     * @return
     */
    @Override
    public R userInfo(String username) {
        if (username.equals("admin")) {
            QueryWrapper<Admin> lambdaQueryWrap = new QueryWrapper();
            lambdaQueryWrap.eq("username", username);
            Admin admin = adminMapper.selectById(username);
            if (admin == null) {
                return R.error(400, "查找失败");
            }
            return R.success("查找成功", admin);
        } else {
            QueryWrapper<Consumer> lambdaQueryWrap = new QueryWrapper();
            lambdaQueryWrap.eq("username", username);
            Consumer consumer = consumerMapper.selectById(username);
            if (consumer == null) {
                return R.error(400, "查找失败");
            }
            return R.success("查找成功", consumer);
        }
    }

    /**
     * 修改密码
     * @param updatePasswordRequest
     * @return
     */
    @Override
    public R updatePassword(AdminDTO updatePasswordRequest) {
        if (!this.verityPasswd(updatePasswordRequest.getUsername(), updatePasswordRequest.getOldPassword())) {
            return R.error(400, "旧密码输入错误");
        }
        Admin admin = new Admin();
        Integer id = updatePasswordRequest.getId();
        admin.setId(id);
        String secretPassword = DigestUtils.md5DigestAsHex((SALT + updatePasswordRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
        admin.setPassword(secretPassword);
        if (adminMapper.updateById(admin) > 0) {
            return R.success("密码修改成功");
        } else {
            return R.error(400, "密码修改失败");
        }
    }

    /**
     * 判断密码是否正确
     * @param username
     * @param password
     * @return
     */
    @Override
    public boolean verityPasswd(String username, String password) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        String secretPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes(StandardCharsets.UTF_8));
        queryWrapper.eq("password", secretPassword);
        return adminMapper.selectCount(queryWrapper) > 0;
    }
}
